package com.qxzn.app.util;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.AlarmClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class AppUtil {

    public static void showLog(Object object) {
        Log.i("测试", object + "");
    }

    public static void showToast(Context context, Object object) {
        Toast.makeText(context, object + "", Toast.LENGTH_LONG).show();
    }

    public static void showShortToast(Context context, Object object) {
        Toast.makeText(context, object + "", Toast.LENGTH_SHORT).show();
    }

    // version
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static boolean openApp(Context context, String packageName) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            AppUtil.showToast(context, "启动失败，应用不存在");
            return false;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(resolveIntent, 0);
        if (resolveInfoList == null || resolveInfoList.size() == 0) {
            AppUtil.showToast(context, "启动失败，应用不存在");
            return false;
        }
        ResolveInfo resolveInfo = resolveInfoList.iterator().next();
        if (resolveInfo != null) {
            String mPackageName = resolveInfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packageName.mainActivityname]
            String className = resolveInfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

            // 设置ComponentName参数1:packageName参数2:MainActivity路径
            ComponentName cn = new ComponentName(mPackageName, className);

            intent.setComponent(cn);
            context.startActivity(intent);
            return true;
        }
        AppUtil.showToast(context, "启动失败，应用不存在");
        return false;
    }

    public static boolean isAppExist(Context context, String packageName) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return false;
        }
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(resolveIntent, 0);
        ResolveInfo resolveInfo = resolveInfoList.iterator().next();
        if (resolveInfo != null) {
            return true;
        }
        return false;
    }

    /**
     * 创建闹钟
     *
     * @param context
     * @param intent  接收的广播
     * @param time    提醒时间(13位时间戳)
     * @param clockId 闹钟id，唯一标识，用于区分闹钟和取消对应的闹钟。(1：提醒闹钟,type为notify_common；)
     */
    public static void MyAlarmClock(Context context, Intent intent, Long time, int clockId) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        intent.setAction("action_clock" + clockId);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, clockId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT < 19) {
            //第一个参数：闹钟类型，第二个参数：开始的时间，第三个参数：间隔时间，第四个参数：操作
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), time - System.currentTimeMillis(), pendingIntent);
//            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);//不重复
        } else {
            //第一个参数：闹钟类型，第二个参数：从当前时间开始隔10秒执行一次，第三个参数：操作，不重复
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
        }
    }

    public static void cancelAlarm(Context context, Intent intent, int clockId) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        intent.setAction("action_clock" + clockId);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, clockId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (intent != null) {
            alarmManager.cancel(pendingIntent);
        }
    }

    /**
     * 创建系统闹钟
     *
     * @param context
     * @param message 闹钟备注
     * @param hour
     * @param minutes
     * @param resId
     */
    public static void createSysAlarm(Context context, String message, ArrayList<Integer> repeatDays, int hour, int minutes, int resId) {
//        ArrayList<Integer> repeatDays = new ArrayList<>();
//        repeatDays.add(Calendar.MONDAY);//周一
//        repeatDays.add(Calendar.TUESDAY);//周二
//        repeatDays.add(Calendar.FRIDAY);//周五

        String packageName = context.getPackageName();
        Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId);
        Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .putExtra(AlarmClock.EXTRA_HOUR, hour)
                .putExtra(AlarmClock.EXTRA_MINUTES, minutes)
                //响铃时提示的信息
                .putExtra(AlarmClock.EXTRA_MESSAGE, message)
                //用于指定该闹铃触发时是否振动
                .putExtra(AlarmClock.EXTRA_VIBRATE, true)
                //一个 content: URI，用于指定闹铃使用的铃声，也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
                //如需使用默认铃声，则无需指定此 extra。
                .putExtra(AlarmClock.EXTRA_RINGTONE, ringtoneUri)
                //如果为true，则调用startActivity()不会进入手机的闹钟设置界面
                .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        if (repeatDays != null && repeatDays.size() > 0) {
            //一个 ArrayList，其中包括应重复触发该闹铃的每个周日。
            // 每一天都必须使用 Calendar 类中的某个整型值（如 MONDAY）进行声明。
            //对于一次性闹铃，无需指定此 extra
            intent.putExtra(AlarmClock.EXTRA_DAYS, repeatDays);
        }
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void cancelSysAlarm(Activity activity, String message, int hour, int minutes, int resId) {//无效
        ArrayList<Integer> testDays = new ArrayList<>();
        testDays.add(Calendar.MONDAY);//周一
        testDays.add(Calendar.TUESDAY);//周二
        testDays.add(Calendar.FRIDAY);//周五

        String packageName = activity.getPackageName();
        Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId);
        Intent intent = new Intent(AlarmClock.ACTION_DISMISS_ALARM)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .putExtra(AlarmClock.EXTRA_ALARM_SEARCH_MODE, AlarmClock.ALARM_SEARCH_MODE_ALL)
                .putExtra(AlarmClock.EXTRA_HOUR, hour)
                .putExtra(AlarmClock.EXTRA_MINUTES, minutes)
                //响铃时提示的信息
                .putExtra(AlarmClock.EXTRA_MESSAGE, message)
                //用于指定该闹铃触发时是否振动
                .putExtra(AlarmClock.EXTRA_VIBRATE, true)
                //一个 content: URI，用于指定闹铃使用的铃声，也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
                //如需使用默认铃声，则无需指定此 extra。
                .putExtra(AlarmClock.EXTRA_RINGTONE, ringtoneUri)
                //一个 ArrayList，其中包括应重复触发该闹铃的每个周日。
                // 每一天都必须使用 Calendar 类中的某个整型值（如 MONDAY）进行声明。
                //对于一次性闹铃，无需指定此 extra
                .putExtra(AlarmClock.EXTRA_DAYS, testDays)
                //如果为true，则调用startActivity()不会进入手机的闹钟设置界面
                .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivity(intent);
        }
    }

    public static String getAppPkgByName(Context context, String appName) {
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> list = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (PackageInfo packageInfo : list) {
            //获取到设备上已经安装的应用的名字,即在AndriodMainfest中的app_name。
            String name = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
            if (appName != null && name != null && (appName.contains(name.toLowerCase()) || name.toLowerCase().contains(appName))) {
                //获取到应用所在包的名字,即在AndriodMainfest中的package的值。
                AppUtil.showLog(name + "---" + appName + "---" + packageInfo.packageName);
                return packageInfo.packageName;
            }
        }
        return null;
    }

//    public static List<AppInfoBean> getAppInfoList(Context context, Map<String, String> pagMap) {
//        List<AppInfoBean> appList = new ArrayList<>();
//        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
//        PackageInfo packageinfo = null;
//        PackageManager packageManager = context.getPackageManager();
//        for (Map.Entry<String, String> entry : pagMap.entrySet()) {
//            try {
//                packageinfo = packageManager.getPackageInfo(entry.getKey(), 0);
//            } catch (PackageManager.NameNotFoundException e) {
//                packageinfo = null;
//                e.printStackTrace();
//            }
//            if (packageinfo != null) {
//                AppInfoBean info = new AppInfoBean();
//                if (TextUtils.isEmpty(entry.getValue())) {
//                    info.setAppName(packageinfo.applicationInfo.loadLabel(packageManager) + "");
//                } else {
//                    info.setAppName(entry.getValue());
//                }
//                info.setAppIcon(packageinfo.applicationInfo.loadIcon(packageManager));
//                info.setAppPackageName(packageinfo.applicationInfo.packageName);
//                appList.add(info);
//            }
//        }
//        return appList;
//    }

    public static Date parseDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Long parseLong(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        try {
            return sdf.parse(dateStr).getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Calendar parseDateToCalendar(Date date) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar;
        }
        return null;
    }

    public static String getDescriptionTime() {
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        if (hour >= 0 && hour < 5) {
            return "凌晨";
        } else if (hour >= 5 && hour < 11) {
            return "早上";
        } else if (hour >= 11 && hour < 13) {
            return "中午";
        } else if (hour >= 13 && hour < 17) {
            return "下午";
        } else if (hour >= 17 && hour < 19) {
            return "傍晚";
        } else {
            return "晚上";
        }
    }

    public static String chargeSecondsToNowTime(String seconds) {
        if (seconds != null && !"".equals(seconds) && !"undefined".equals(seconds.toLowerCase())) {
            long time = Long.parseLong(seconds) * 1000 + 8 * 3600 * 1000;
            //long time = Long.parseLong(seconds)*1000;
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format2.format(new Date(time));
        }
        return "";
    }

    public static String chargeSecondsToNowTime(long seconds) {
        long time = seconds + 8 * 3600 * 1000;
        //long time = Long.parseLong(seconds)*1000;
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format2.format(new Date(time));
    }

//    public static String getNextDate(String date){
//        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
//        try {
//            Date temp = dft.parse("传入的日期字符串");
//            Calendar cld = Calendar.getInstance();
//            cld.setTime(temp);
//            cld.add(Calendar.DATE, 1);
//            temp = cld.getTime();
//            //获得下一天日期字符串
//            String nextDay = dft.format(temp);
//            return nextDay;
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    public static List<String> getSevenDay() {
        List<String> days = new ArrayList<>();
        //DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 8; i++) {
            Calendar mCalendar = Calendar.getInstance();
            //年
            int year = mCalendar.get(Calendar.YEAR);
            //月
            int month = mCalendar.get(Calendar.MONTH) + 1;
            //日
            int day = mCalendar.get(Calendar.DAY_OF_MONTH);

            mCalendar.add(Calendar.DATE, i);

            days.add(mCalendar.get(Calendar.YEAR) + "-" + (mCalendar.get(Calendar.MONTH) + 1) + "-" + mCalendar.get(Calendar.DAY_OF_MONTH));
        }
        return days;
    }

    public static void startActivity(Context context, String activity, Map<String, String> params) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(context, activity));
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    intent.putExtra(entry.getKey(), entry.getValue());
                }
            }
            context.startActivity(intent);
        } catch (Exception e) {
            AppUtil.showLog("页面不存在：" + activity);
        }
    }

    public static void startActivity(Context context, Class<?> cls, Map<String, String> params) {
        try {
            Intent intent = new Intent(context, cls);
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    intent.putExtra(entry.getKey(), entry.getValue());
                }
            }
            context.startActivity(intent);
        } catch (Exception e) {
            AppUtil.showLog("页面不存在：" + cls);
        }
    }

    public static String getAssetsText(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 隐藏软件盘
     *
     * @param token
     */
    public static void hideSoftInput(Context context, IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
